<?php
namespace app\install\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
error_reporting(E_ERROR | E_PARSE );
class Index  extends \app\BaseController{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        if(file_exists(app_path()."install.lock")){
            die("网站已经安装过，如要重新安装，请删除:app/install/install.lock");
        }
    }    
    //首页
    public function index() {
    	return View::fetch();
    }
    
    public function step2(){
        if(file_exists(root_path().'.env')){
            //@unlink(root_path.'.env');
        }
        $data=array();
        $data['phpversion'] = @ phpversion();
        $data['os']=PHP_OS;
        $tmp = function_exists('gd_info') ? gd_info() : array();
        $server = $_SERVER["SERVER_SOFTWARE"];
        $host = (empty($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_HOST"] : $_SERVER["SERVER_ADDR"]);
        $name = $_SERVER["SERVER_NAME"];
        $max_execution_time = ini_get('max_execution_time');
        $allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
        $allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
        $safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');
        
        $err = 0;
        if (empty($tmp['GD Version'])) {
            $gd = '<font color=red>[×]Off</font>';
            $err++;
        } else {
            $gd = '<font color=green>[√]On</font> ' . $tmp['GD Version'];
        }
        
        if (class_exists('pdo')) {
            $data['pdo'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['pdo'] = '<i class="fa fa-remove error"></i> 未开启';
            $err++;
        }
        
        if (extension_loaded('pdo_mysql')) {
            $data['pdo_mysql'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['pdo_mysql'] = '<i class="fa fa-remove error"></i> 未开启';
            $err++;
        }
        
        if (extension_loaded('curl')) {
            $data['curl'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['curl'] = '<i class="fa fa-remove error"></i> 未开启';
            $err++;
        }
        
        if (extension_loaded('gd')) {
            $data['gd'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['gd'] = '<i class="fa fa-remove error"></i> 未开启';
            if (function_exists('imagettftext')) {
                $data['gd'].='<br><i class="fa fa-remove error"></i> FreeType Support未开启';
            }
            $err++;
        }
        
        if (extension_loaded('mbstring')) {
            $data['mbstring'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['mbstring'] = '<i class="fa fa-remove error"></i> 未开启';
            if (function_exists('imagettftext')) {
                $data['mbstring'].='<br><i class="fa fa-remove error"></i> FreeType Support未开启';
            }
            $err++;
        }
        
        if (ini_get('file_uploads')) {
            $data['upload_size'] = '<i class="fa fa-check correct"></i> ' . ini_get('upload_max_filesize');
        } else {
            $data['upload_size'] = '<i class="fa fa-remove error"></i> 禁止上传';
        }
        
        if (function_exists('session_start')) {
            $data['session'] = '<i class="fa fa-check correct"></i> 支持';
        } else {
            $data['session'] = '<i class="fa fa-remove error"></i> 不支持';
            $err++;
        }
        $folders = array(
            root_path().'runtime',
            base_path().'data',
            public_path().'upload',
        );
        $new_folders=array();
        foreach($folders as $dir){
            $Testdir = $dir;
            sp_dir_create($Testdir);
            if(sp_testwrite($Testdir)){
                $new_folders[$dir]['w']=true;
            }else{
                $new_folders[$dir]['w']=false;
                $err++;
            }
            if(is_readable($Testdir)){
                $new_folders[$dir]['r']=true;
            }else{
                $new_folders[$dir]['r']=false;
                $err++;
            }
        }
        $data['folders']=$new_folders;
        View::assign($data);
    	return View::fetch();
    }
    
    public function step3(){
    	return View::fetch();
    }
    
    public function step4(){
        if(request()->isPost()){
            echo  View::fetch();
            $data=Request::param();
            //创建数据库
            $dbhost=$data['dbhost'];
            $dbuser=$data['dbuser'];
            $dbpw=$data['dbpw'];
            $dbname=$data['dbname'];
            $dbport=$data['dbport'];

            $h_param = array(
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            );        
            try{
                $conn = new \PDO("mysql:host=$dbhost;port=$dbport;dbname=$dbname;", $dbuser, $dbpw,$h_param);

            } catch (\PDOException $e) {
                throw new \ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31);

            }                
            //创建数据表
            $sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8mb4";
            $conn->query($sql);
            $table_prefix=$data['dbprefix'];
            sp_execute_sql($conn,"install.sql", $table_prefix);
            //更新配置信息
            sp_update_site_configs($data);
            //创建管理员
            sp_create_admin_account($conn, $table_prefix,$data);
            //生成网站配置文件
            sp_create_config($data);
            session("install",1);
            echo "<script type=\"text/javascript\">isOk()</script>";
        }else{
            exit;
        }
    }
    
    public function step5(){
        if(!session("install")){
            $this->error("非法访问");
        }        
        //生成lock锁文件
        file_put_contents(app_path()."install.lock","lock");       
        return View::fetch();
    }
    public function check_db()
    {
        $data=Request::param();
        // 数据库设定
        $config = array(
            'host' => $data['DB_HOST'],
            'dbname' => $data['DB_NAME'],
            'port' => $data['DB_PORT'],
            'user' => $data['DB_USER'],
            'password' => $data['DB_PWD'],
            'pconnect' => 0,
            'charset' => ''
        );
        // 创建数据连接
        $host = $config['host'];
        $dbname = $config['dbname'];
        $port = $config['port'];
        $user = $config['user'];
        $password = $config['password'];
        
        $dsn = "mysql:host=$host;port=$port;dbname=$dbname;";

        try {
            $h_param = array(
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            );
            $conn = new \PDO($dsn, $user, $password, $h_param);
        } catch (\PDOException $e) {
            throw new \ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31);

        }      
        echo "ok";
    }

}

